package org.infodavid.common.util;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * The Class CollectionsUtil.
 */
public final class CollectionsUtil {

	/** The Constant log. */
	private static final Log LOGGER = LogFactory.getLog(CollectionsUtil.class);

	/** The singleton. */
	private static WeakReference<CollectionsUtil> singleton = null;

	/**
	 * returns the singleton.
	 * @return <code>CollectionsUtil</code>
	 */
	public static synchronized CollectionsUtil getInstance() {
		if (singleton == null || singleton.get() == null) {
			singleton = new WeakReference<CollectionsUtil>(new CollectionsUtil());
		}

		return singleton.get();
	}

	/** The is debug enabled. */
	@SuppressWarnings("unused")
  private final boolean isDebugEnabled = LOGGER.isDebugEnabled();

	/**
	 * Instantiates a new arrays utility.
	 */
	private CollectionsUtil() {
		super();
	}

	/**
	 * Put all values as string values.
	 * @param from the from
	 * @param to the to
	 */
	public void putAll(final Map<String,?> from, final Map<String,String> to) {
		if (!(from == null || from.isEmpty())) {
			Object value;

			for (final Map.Entry<String,?> entry : from.entrySet()) {
				value = entry.getValue();

				if (value != null) {
					if (value instanceof String) {
						to.put(entry.getKey(), (String)value);
					}
					else {
						to.put(entry.getKey(), value.toString());
					}
				}
			}
		}
	}

	/**
	 * Sub list.
	 * @param <E> the element type
	 * @param source the source
	 * @param fromIndex the from index
	 * @param pageSize the page size
	 * @return the elements or null if source is null
	 */
	public <E> List<E> subList(final List<E> source, final int fromIndex, final int pageSize) {
		if (source == null) {
			return source;
		}

		final int size = source.size();

		if (size == 0) {
			return new ArrayList<E>();
		}

		final int from;

		if (fromIndex < 0 || fromIndex >= size) {
			from = 0;
		}
		else {
			from = fromIndex;
		}

		int to = from + pageSize;

		if (to <= from || to >= size) {
			to = size - 1;
		}

		return source.subList(from, to);
	}
}
